﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace Sherwood.Configuration
{
    ///<summary>
    /// Contains configuration extension methods
    ///</summary>
    public static class ExtensionMethods
    {
        ///<summary>
        /// Read a configuration file as xml. Returns null if file does not exist.
        ///</summary>
        /// <param name="fileName">A relative or virtual filename (depending on repository type)</param>
        ///<exception cref="ArgumentNullException"></exception>
        public static XmlReader CreateXmlReaderSafe(this IConfigRepository config, string fileName)
        {
            if (config == null) throw new ArgumentNullException("config");

            var textReader = config.CreateTextReader(fileName);
            return textReader == null ? null : XmlReader.Create(textReader);
        }

        ///<summary>
        /// Read a configuration file as xml. Throws an exception if file does not exist.
        ///</summary>
        /// <param name="fileName">A relative or virtual filename (depending on repository type)</param>
        ///<exception cref="ArgumentNullException"></exception>
        public static XmlReader CreateXmlReader(this IConfigRepository config, string fileName)
        {
            var reader = config.CreateXmlReaderSafe(fileName);
            if (reader == null)
                throw new ArgumentException(fileName + " does not exist", fileName);
            return reader;
        }

        /// <summary>
        /// Read a configuration file as text. Throws an exception if file does not exist.
        /// </summary>
        /// <param name="fileName">A relative or virtual filename (depending on repository type)</param>
        ///<exception cref="ArgumentException"></exception>
        ///<exception cref="ArgumentNullException"></exception>
        public static TextReader CreateTextReader(this IConfigRepository config, string fileName)
        {
            var reader = config.CreateTextReaderSafe(fileName);
            if (reader == null)
                throw new ArgumentException(fileName + " does not exist", fileName);
            return reader;
        }
    }
}